<template>
  <div id="register" v-title data-title="注册 - 博乐阁">
    <!--<video preload="auto" class="me-video-player" autoplay="autoplay" loop="loop">
          <source src="../../static/vedio/sea.mp4" type="video/mp4">
      </video>-->

    <div class="me-login-box me-login-box-radius">
      <h1>博乐阁 注册</h1>

      <el-form ref="userForm" :model="userForm" :rules="rules">
        <el-form-item prop="account">
          <el-input placeholder="用户名" v-model="userForm.account"></el-input>
        </el-form-item>

        <el-form-item prop="nickname">
          <el-input placeholder="昵称" v-model="userForm.nickname"></el-input>
        </el-form-item>

        <el-form-item prop="password">
          <el-input placeholder="密码" type="password" v-model="userForm.password"></el-input>
        </el-form-item>

        <el-form-item prop="email">
          <el-input placeholder="邮箱" type="email" v-model="userForm.email"></el-input>
        </el-form-item>

        <el-form-item prop="code">
            <el-input
              class="bind_code_input code"
              v-model="userForm.code"
              type="text"
              placeholder="请输入验证码"
            />
            <el-button
              @click="doSendCode"
              class="bind_code_gain"
              :disabled="sendObj.isSend"
            >{{ sendObj.sendCodeText }}
            </el-button
            >
        </el-form-item>

        <el-form-item size="small" class="me-login-button">
          <el-button type="primary" @click.native.prevent="register('userForm')">注册</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
  import {register} from '@/api/login'
  import {accountExist, emailExist} from "../api/user";
  import {registerSendCode} from "../api/login";

  export default {
    name: 'Register',
    data() {
      return {
        emailPattern: /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(.[a-zA-Z0-9_-]+)+$/,
        userForm: {
          account: '',
          nickname: '',
          password: '',
          code: '',
          tempToken: '',
          email: ''
        },
        sendObj: {
          sendInterval: 60,
          sendCodeText: '发送邮箱验证码',
          isSend: false,
          timer: null
        },
        rules: {
          account: [
            {required: true, message: '请输入用户名', trigger: 'blur'},
            {max: 10, message: '不能大于10个字符', trigger: 'blur'},
            {validator: this.validateAccount, trigger: 'blur'},
          ],
          nickname: [
            {required: true, message: '请输入昵称', trigger: 'blur'},
            {max: 10, message: '不能大于10个字符', trigger: 'blur'}
          ],
          password: [
            {required: true, message: '请输入密码', trigger: 'blur'},
            {max: 10, message: '不能大于10个字符', trigger: 'blur'}
          ],
          code: [
            {required: true, message: '请输入验证码', trigger: 'blur'},
            {min: 6, max: 6, message: '请输入6位验证码', trigger: 'blur'}
          ],
          email: [
            {required: true, message: '请输入邮箱地址', trigger: 'blur'},
            {type: 'email', message: '邮箱地址格式错误', trigger: 'blur'},
            {validator: this.validateEmail, trigger: 'blur'},
          ]
        }
      }
    },
    methods: {
      register(formName) {
        let that = this
        this.$refs[formName].validate((valid) => {
          if (valid) {
            that.$store.dispatch('register', that.userForm).then(() => {
              that.$message({message: '注册成功，快发布你的第一篇文章吧', type: 'success', showClose: true});
              that.$router.push({path: '/'})
            }).catch((error) => {
              if (error !== 'error') {
                that.$message({message: '注册失败', type: 'error', showClose: true});
              }
            })
          } else {
            return false;
          }
        });
      },
      // 发送验证码
      async doSendCode() {
        if (this.userForm.email === '' || !this.emailPattern.test(this.userForm.email)) {
          this.$message({
            message: '邮箱为空或不符合邮箱规则',
            type: 'warning'
          })
          return
        }
        let resp1 = await emailExist(this.userForm.email)
        if (!resp1.success || resp1.data) {
          // 请求不成功或者邮箱重复
          this.$message({
            message: '邮箱已重复',
            type: 'warning'
          })
          return
        }
        let resp2 = await registerSendCode(this.userForm.email)
        if (!resp2.success || resp2.data === '') {
          this.$message({
            message: '验证码发送失败，可能是因为邮箱已重复',
            type: 'warning'
          })
          return
        }
        // 保存临时令牌
        this.userForm.tempToken = resp2.data
        this.sendObj.sendCodeText = this.sendObj.sendInterval
        this.sendObj.isSend = true
        clearInterval(this.sendObj.timer)
        this.sendObj.timer = setInterval(() => {
          if (this.sendObj.sendCodeText === 0) {
            clearInterval(this.sendObj.timer)
            this.sendObj.sendCodeText = '发送验证码'
            this.sendObj.isSend = false
            return
          }
          let time
          try {
            time = parseInt(this.sendObj.sendCodeText)
          } catch (e) {
            time = 60
          }
          this.sendObj.sendCodeText = time - 1
        }, 1000)
      },
      // 判断用户名是否重复
      validateAccount(rule, value) {
        return new Promise((resolve, reject) => {
          accountExist(value).then(resp => {
            if (resp.success && !resp.data) {
              // 请求成功，并且未重复
              resolve()
            } else {
              reject('用户名已重复')
            }
          })
        })
      },
      // 判断邮箱是否重复
      validateEmail(rule, value) {
        return new Promise((resolve, reject) => {
          emailExist(value).then(resp => {
            if (resp.success && !resp.data) {
              // 请求成功，并且未重复
              resolve()
            } else {
              reject('邮箱已重复')
            }
          })
        })
      }
    }
  }
</script>

<style scoped>
  #login {
    min-width: 100%;
    min-height: 100%;
  }

  .me-video-player {
    background-color: transparent;
    width: 100%;
    height: 100%;
    object-fit: fill;
    display: block;
    position: absolute;
    left: 0;
    z-index: 0;
    top: 0;
  }

  .me-login-box {
    position: absolute;
    width: 300px;
    height: 400px;
    background-color: white;
    margin-top: 150px;
    margin-left: -180px;
    left: 50%;
    padding: 30px;
  }

  .me-login-box-radius {
    border-radius: 10px;
    box-shadow: 0px 0px 1px 1px rgba(161, 159, 159, 0.1);
  }

  .me-login-box h1 {
    text-align: center;
    font-size: 24px;
    margin-bottom: 20px;
    vertical-align: middle;
  }

  .me-login-design {
    text-align: center;
    font-family: 'Open Sans', sans-serif;
    font-size: 18px;
  }

  .me-login-design-color {
    color: #5FB878 !important;
  }

  .me-login-button {
    text-align: center;
  }

  .me-login-button button {
    width: 100%;
  }

  /* ------------------------------- */
  .bind_code {
    position: relative;
  }

  /*.code /deep/ .el-input__suffix {*/
  /*  right: 97px;*/
  /*}*/

  .bind_code_gain {
    border: 0;
    background: none;
    padding: 0 0 0 10px;
    border-radius: 0;
    position: absolute;
    top: calc(50% - 9px);
    right: 10px;
    font-size: 14px;
    line-height: 18px;
    cursor: pointer;
    border-left: 1px solid #d8d8d8;
  }

</style>
